package ru.len.cafe.ejb;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Stateless;

import ru.len.cafe.ejb.dao.EmployeDao;
import ru.len.cafe.ejb.exception.CacheException;
import ru.len.cafe.ejb.security.HashGenerator;
import ru.len.cafe.entity.model.Employe;

/**
 * Bean, that takes login and password of User and gives him
 * @author Stanislav Chetvertkov
 *
 */

@Singleton
public class LoginEJB {

    /**
     * Cache of users in the system
     */
    private Map<String, Employe> cache = new HashMap<String, Employe>();
    
    /**
     * 
     * @param employe
     * @return
     * @throws CacheException
     */
    public String addToCache(String hash, Employe employe) throws CacheException{
    	if(cache.containsValue(employe)){ 
    		throw new CacheException();
    	}else{
    		cache.put(hash, employe);
    	}
    	return hash;
    }
    
    /**
     * Clean cache every 30 minutes 
     */
    @Schedule(minute = "*/30", hour = "*", persistent = false)
    public void refreshCache(){
	cache.clear();
    }
    
    /**
     * 
     * @param hash
     * @return
     */
    public Employe getEmployeFromCache(String hash){
	return cache.get(hash);
    }

    /**
     * Gets 
     * @param login. String login
     * @param password
     * @return
     * @throws NoSuchAlgorithmException
     */
    public String login(String login, String password) throws NoSuchAlgorithmException{
    	/* 1. Check whether employe exist in the system */
    	EmployeDao employeDao = new EmployeDao();
    	Employe employe = employeDao.findEmployeByLogin(login);
	
    	if ( employe == null ){
    		return null;
    	}
	
	/* 2. Check whether password is correct*/
    	if (employe.getPassword() == HashGenerator.hashPassword(password)){
	    
    		String temp = 
    			HashGenerator.
    			generateHash(employe);
	    
    		try {
    			addToCache(temp, employe);
    		} catch (CacheException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}

    		return temp;
    	}else{
    		return null;
    	}

    }
    
}
